import React, { useState, useCallback } from 'react'
import { Search, X, Settings } from 'lucide-react'

export interface SearchOptions {
  query: string
  searchIn: 'key' | 'value' | 'both'
  caseSensitive: boolean
  useRegex: boolean
  highlightResults: boolean
}

interface EnhancedSearchProps {
  onSearch: (options: SearchOptions) => void
  onClear: () => void
  loading?: boolean
  resultCount?: number
  totalCount?: number
}

export default function EnhancedSearch({
  onSearch,
  onClear,
  loading = false,
  resultCount,
  totalCount
}: EnhancedSearchProps) {
  const [searchOptions, setSearchOptions] = useState<SearchOptions>({
    query: '',
    searchIn: 'both',
    caseSensitive: false,
    useRegex: false,
    highlightResults: true
  })
  
  const [showAdvanced, setShowAdvanced] = useState(false)

  const handleSearch = useCallback((e: React.FormEvent) => {
    e.preventDefault()
    if (searchOptions.query.trim()) {
      onSearch(searchOptions)
    }
  }, [searchOptions, onSearch])

  const handleClear = useCallback(() => {
    setSearchOptions(prev => ({ ...prev, query: '' }))
    onClear()
  }, [onClear])

  const updateOption = useCallback((key: keyof SearchOptions, value: any) => {
    setSearchOptions(prev => ({ ...prev, [key]: value }))
  }, [])

  return (
    <div className="space-y-3">
      {/* 主搜索区域 */}
      <form onSubmit={handleSearch} className="flex items-center space-x-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
          <input
            type="text"
            placeholder="搜索消息内容..."
            value={searchOptions.query}
            onChange={(e) => updateOption('query', e.target.value)}
            className="w-full pl-10 pr-10 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary-500 focus:border-transparent"
          />
          {searchOptions.query && (
            <button
              type="button"
              onClick={handleClear}
              className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        
        <button
          type="submit"
          disabled={!searchOptions.query.trim() || loading}
          className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
        >
          {loading && <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>}
          <span>搜索</span>
        </button>
        
        <button
          type="button"
          onClick={() => setShowAdvanced(!showAdvanced)}
          className="p-2 border border-gray-300 rounded-md hover:bg-gray-50"
          title="高级选项"
        >
          <Settings className="h-4 w-4" />
        </button>
      </form>

      {/* 搜索结果统计 */}
      {resultCount !== undefined && totalCount !== undefined && (
        <div className="text-sm text-gray-600">
          {searchOptions.query ? (
            <span>
              找到 <span className="font-medium text-primary-600">{resultCount}</span> 条匹配结果
              (共 {totalCount} 条消息)
            </span>
          ) : (
            <span>共 {totalCount} 条消息</span>
          )}
        </div>
      )}

      {/* 高级搜索选项 */}
      {showAdvanced && (
        <div className="bg-gray-50 p-4 rounded-lg space-y-3">
          <h4 className="text-sm font-medium text-gray-700">搜索选项</h4>
          
          {/* 搜索范围 */}
          <div>
            <label className="block text-sm text-gray-600 mb-2">搜索范围:</label>
            <div className="flex space-x-4">
              <label className="flex items-center">
                <input
                  type="radio"
                  name="searchIn"
                  value="both"
                  checked={searchOptions.searchIn === 'both'}
                  onChange={(e) => updateOption('searchIn', e.target.value)}
                  className="mr-2"
                />
                <span className="text-sm">Key + Value</span>
              </label>
              <label className="flex items-center">
                <input
                  type="radio"
                  name="searchIn"
                  value="key"
                  checked={searchOptions.searchIn === 'key'}
                  onChange={(e) => updateOption('searchIn', e.target.value)}
                  className="mr-2"
                />
                <span className="text-sm">仅 Key</span>
              </label>
              <label className="flex items-center">
                <input
                  type="radio"
                  name="searchIn"
                  value="value"
                  checked={searchOptions.searchIn === 'value'}
                  onChange={(e) => updateOption('searchIn', e.target.value)}
                  className="mr-2"
                />
                <span className="text-sm">仅 Value</span>
              </label>
            </div>
          </div>

          {/* 搜索选项 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={searchOptions.caseSensitive}
                onChange={(e) => updateOption('caseSensitive', e.target.checked)}
                className="mr-2 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
              />
              <span className="text-sm">区分大小写</span>
            </label>
            
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={searchOptions.useRegex}
                onChange={(e) => updateOption('useRegex', e.target.checked)}
                className="mr-2 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
              />
              <span className="text-sm">正则表达式</span>
            </label>
            
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={searchOptions.highlightResults}
                onChange={(e) => updateOption('highlightResults', e.target.checked)}
                className="mr-2 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
              />
              <span className="text-sm">高亮显示</span>
            </label>
          </div>

          {/* 快速搜索模板 */}
          <div>
            <label className="block text-sm text-gray-600 mb-2">快速搜索:</label>
            <div className="flex flex-wrap gap-2">
              {[
                { label: '用户相关', query: 'user', searchIn: 'value' as const },
                { label: '订单相关', query: 'order|ORD', searchIn: 'value' as const, useRegex: true },
                { label: '错误信息', query: 'error|fail|异常', searchIn: 'value' as const, useRegex: true },
                { label: '系统消息', query: 'system|系统', searchIn: 'value' as const, useRegex: true }
              ].map((template, index) => (
                <button
                  key={index}
                  type="button"
                  onClick={() => {
                    setSearchOptions(prev => ({
                      ...prev,
                      query: template.query,
                      searchIn: template.searchIn,
                      useRegex: template.useRegex || false
                    }))
                  }}
                  className="px-3 py-1 text-xs bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                >
                  {template.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// 高亮显示组件
export function HighlightText({ 
  text, 
  searchQuery, 
  caseSensitive = false, 
  useRegex = false 
}: {
  text: string
  searchQuery: string
  caseSensitive?: boolean
  useRegex?: boolean
}) {
  if (!searchQuery || !text) {
    return <span>{text}</span>
  }

  try {
    let regex: RegExp
    
    if (useRegex) {
      const flags = caseSensitive ? 'g' : 'gi'
      regex = new RegExp(searchQuery, flags)
    } else {
      const escapedQuery = searchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
      const flags = caseSensitive ? 'g' : 'gi'
      regex = new RegExp(escapedQuery, flags)
    }

    const parts = text.split(regex)
    const matches = text.match(regex) || []

    return (
      <span>
        {parts.map((part, index) => (
          <React.Fragment key={index}>
            {part}
            {index < matches.length && (
              <mark className="bg-yellow-200 text-yellow-900 px-1 rounded">
                {matches[index]}
              </mark>
            )}
          </React.Fragment>
        ))}
      </span>
    )
  } catch (error) {
    // 如果正则表达式无效，返回原文本
    return <span>{text}</span>
  }
}
